package com.cai.primeton.controller;

import com.cai.primeton.entity.PBorrow;
import com.cai.primeton.entity.PUser;
import com.cai.primeton.entity.R;
import com.cai.primeton.repository.BorrowRepo;
import com.cai.primeton.service.BorrowService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @version 1.0
 * @author：蔡松坡
 * @date：2021/7/1 16 : 28
 * @package：com.cai.primeton.controller
 */
@Controller
@Api(tags = "借阅管理")
public class BorrowController {

//    @Autowired
//    private BorrowRepo borrowRepo;

    @Autowired
    private BorrowService borrowService;

    @GetMapping("/borrow/list")
    public String borrow(){

        return "borrow/borrowbook";
    }

    @GetMapping("/borrow/bkBorrow")
    public String bookBorrow(Model model){

        return "borrow/borrow";
    }

    /**
     * 借阅
     * @param pBorrow
     * @return
     */
    @ApiOperation(value = "借阅图书",notes = "需要传入借阅信息")
//    @ApiImplicitParam(name = "PBorrow")
    @PostMapping("/borrow/insert")
    @ResponseBody
    public Map borrow(PBorrow pBorrow){
        System.out.println("pBorrow  -->>"+pBorrow);
        pBorrow.setState("借阅");
        pBorrow.setPresstime(new Date());
        borrowService.save(pBorrow);
        R r = new R(200,"success");
        return r.result();
    }

    /**
     * 归还成功  把借阅状态修改为完成
     * @param id
     * @return
     */
    @ApiOperation(value = "归还图书",notes = "归还成功，就把借阅状态改变为完成")
    @ApiImplicitParam(name = "id",value = "归还图书的id")
    @GetMapping("/borrow/back/{id}")
    @ResponseBody
    public Map backBook(@PathVariable("id") Long id){
        borrowService.updateState("完成",id);
        R r = new R(200,"success");
        return r.result();
    }

    /**
     * 根据用户账号查询该用户的借阅记录
     * @param account
     * @return
     */
    @ApiOperation(value = "根据用户账号查询该用户的借阅记录",notes = "查询用户的所有借阅记录")
    @ApiImplicitParam(name = "account",value = "用户的账号")
    @GetMapping("/borrow/findBorrow/{account}")
    @ResponseBody
    public List findBorrowsForUser(@PathVariable("account") String account){
        List<PBorrow> allByUseraccount = borrowService.findAllByUseraccount(account);
        return allByUseraccount;
    }

    @GetMapping("/borrow/user")
    public String userBorrow(HttpSession session,Model model){
        PUser userSession = (PUser) session.getAttribute("userSession");
        List<PBorrow> allByUseraccount = borrowService.findAllByUseraccount(userSession.getAccount());
        model.addAttribute("borrows",allByUseraccount);
        return "borrow/userborrow";
    }
}
